<script lang="ts" setup>
import { FormInstance, FormRules } from "element-plus";
import { computed, reactive, ref } from "vue";
import { PayInfoApi } from "@/Api";

interface Props {
   modelValue: boolean;
   payInfo?: PayInfo.InlineTable;
   merchantList?: Merchant.SearchResult[];
}

const props = withDefaults(defineProps<Props>(), {
   modelValue: false
});

const emit = defineEmits<{
   (e: "update:modelValue", value: boolean): void;
}>();

const dialogVisible = computed({
   get: () => props.modelValue,
   set: value => {
      if (!value) formRef.value?.resetFields();
      emit("update:modelValue", value);
   }
});

const payInfo = computed(() => props.payInfo);
const merchantList = computed(() => props.merchantList);
const formRef = ref<FormInstance>();
const loading = reactive({ update: false });
const disable = reactive({ update: false });

const form = reactive<PayInfo.Update>({
   pay_id: "",
   name: "",
   fee: 0,
   level: "",
   school: "",
   category: "",
   major: "",
   batch: "",
   school_year: "",
   merchant: ""
});

const formRules = reactive<FormRules>({
   fee: [
      { required: true, message: "金额为必填", trigger: "blur" },
      { type: "number", message: "金额只能为数字", trigger: "change" },
      {
         validator(rule, value, callback, source, options) {
            if (value > 0) {
               callback();
            } else {
               callback(new Error("金额必须大于 0"));
            }
         },
         trigger: "change"
      }
   ],
   name: { required: true, message: "学生姓名必填", trigger: "blur" },
   level: { required: true, message: "层次为必填", trigger: "blur" },
   school: { required: true, message: "学校为必填", trigger: "blur" },
   category: { required: true, message: "类别为必填", trigger: "blur" },
   major: { required: true, message: "专业为必填", trigger: "blur" },
   batch: { required: true, message: "批次为必填", trigger: "blur" },
   school_year: { required: true, message: "学年为必填", trigger: "blur" },
   merchant: { required: true, message: "付款商户为必选", trigger: "blur" }
});

/** 修改缴费信息 */
async function handlerClick(formRef?: FormInstance) {
   if (!formRef) return;
   formRef.validate(async (valid, fields) => {
      if (!valid) return;
      if (!payInfo.value) return ElMessage.error("系统错误");
      if (form.fee < 0) return ElMessage.warning("金额必须大于 0");

      /** 当金额大于 5000 时，弹窗提示 */
      let alert = false;
      if (form.fee > 5000) {
         try {
            await ElMessageBox.alert("当前金额大于 5000 元，是否继续", "提示", {
               confirmButtonText: "继续",
               cancelButtonText: "取消",
               showCancelButton: true,
               distinguishCancelAndClose: true
            });
         } catch (error) {
            alert = true;
         }
      }
      if (alert) return;

      const params: PayInfo.Update = {
         ...form,
         fee: form.fee * 100
      };

      const { code } = await PayInfoApi.Update(params);
      if (code === 200) {
         ElMessage.success("添加成功");
         dialogVisible.value = false;
      }
   });
}

function handlerOpen() {
   if (!payInfo.value) return;

   form.fee = Number(payInfo.value.fee) / 100;
   form.name = payInfo.value.name;
   form.pay_id = payInfo.value.pay_id;
   form.level = payInfo.value.level;
   form.school = payInfo.value.school;
   form.category = payInfo.value.category;
   form.major = payInfo.value.major;
   form.batch = payInfo.value.batch;
   form.school_year = payInfo.value.school_year;
   form.merchant = payInfo.value.merchant;
}

// 窗口关闭，重置数据
function handlerClosed() {
   if (!formRef.value) return;
   formRef.value.resetFields();
}
</script>

<template>
   <el-dialog
      v-model="dialogVisible"
      ref="dialog"
      title="编辑缴费信息"
      width="500px"
      draggable
      append-to-body
      @open="handlerOpen"
      @closed="handlerClosed">
      <el-form ref="formRef" :model="form" :rules="formRules">
         <el-form-item label="缴费金额" prop="fee">
            <el-input-number v-model="form.fee" controls-position="right" /> 元
         </el-form-item>
         <el-form-item label="学生姓名" prop="name">
            <el-input v-model="form.name" placeholder="请输入学生姓名" />
         </el-form-item>
         <el-form-item label="报考层次" prop="level">
            <el-input v-model="form.level" placeholder="请输入层次" />
         </el-form-item>
         <el-form-item label="报考学校" prop="school">
            <el-input v-model="form.school" placeholder="请输入报考学校" />
         </el-form-item>
         <el-form-item label="报考类别" prop="category">
            <el-input v-model="form.category" placeholder="请输入报考类别" />
         </el-form-item>
         <el-form-item label="报考专业" prop="major">
            <el-input v-model="form.major" placeholder="请输入报考专业" />
         </el-form-item>
         <el-form-item label="所属批次" prop="batch">
            <el-input v-model="form.batch" placeholder="请输入所属批次" />
         </el-form-item>
         <el-form-item label="学习年限" prop="school_year">
            <el-input v-model="form.school_year" placeholder="请输入学年" />
         </el-form-item>
         <el-form-item label="付款商户" prop="merchant">
            <el-select v-model="form.merchant" placeholder="请选择付款商户">
               <el-option v-for="item in merchantList" :key="item.id" :label="`${item.name}(${item.code})`" :value="item.id" />
            </el-select>
         </el-form-item>
      </el-form>
      <template #footer>
         <span class="dialog-footer">
            <el-button :loading="loading.update" :disabled="disable.update" type="primary" @click="handlerClick(formRef)">
               保存
            </el-button>
         </span>
      </template>
   </el-dialog>
</template>

<style lang="scss" scoped>
.el-form {
   box-sizing: border-box;
   padding-inline: 20px;
}
.el-input,
.el-select {
   width: 100%;
}
</style>
